# !/usr/bin/env python3  /*设定脚本文件直接能执行*/
# -*- coding:utf-8 -*-   /*设置编码*/
"""
@Author: zhengjiantang
@Software: PyCharm
@File: tIniHelper.py
@Time: 2020/5/11 10:15c
@Function：ctIniHelper：INI配置文件操作模块
"""
import copy
import os
import sys

from configobj import *

sys.path.append(os.path.dirname(os.path.realpath(__file__)))


class ctIniHelper:
    """
    配置文件操作通用类：
    1、f_Read(self, dicRead={'Section': '', 'Option': '', 'Value': '', 'FilePath': '', 'SectionList': 0}, )： 读配置文件；
    2、f_Write(self, dicWrite={'Section': 0, 'Option': 0, 'Value': 0, 'FilePath': ''})： 写配置文件，一次只能写入一个键值对，需要文件存在的前提下才能写；
    3、f_Create(self, dicWrite={'Section': 0, 'Option': 0, 'Value': 0, 'FilePath': ''})： 写配置文件，一次只能写入一个键值对，文件路径不存在则创建；
    4、f_Clear(self, dicWrite={'Section': 0, 'FilePath': ''})：清空配置文件。
    """
    # 类属性
    __m_property = {'name': 'ctFileINI', }
    # 文件对象
    __m_file = None
    # 文件名称
    __m_strNameOfFile = ' '

    # 初始化
    def __init__(self, strFilePath):
        ir = 0
        self.__m_strNameOfFile = copy.deepcopy(strFilePath)
        self.__m_strNameOfFile.strip()
        try:
            self.__m_file = ConfigObj(self.__m_strNameOfFile, encoding='UTF8')
        except Exception as err:
            errStr = '配置文件解析错误' + self.__m_strNameOfFile + '  ' + str(err)
            raise errStr

    # 析构函数
    def __del__(self):
        ir = 0
        if (self.__m_file):
            del self.__m_file
            self.__m_file = None
            ir = 1
        return ir

    # 读配置文件
    def f_Read(self, dicRead={'Section': '', 'Option': '', 'Value': '', 'FilePath': '', 'SectionList': 0}, ):
        """
        function:  Read Dic from INI.file
              in:  Read ini file，Get a parameter Dic
                   param dicRead: 将读取到的文件写入该字典中
                   Section : ini文件中带[]的项
                   SectionList : ini文件中带[]的项的列表
                   FilePath : 文件路径
                   Option : 选项
                   OptionDic : 选项列表
             out:  None
          return:  int >0 ok, <0 somewrong
          others:  读配置文件
        """
        ir = 0
        strName = ''

        if dicRead.get('FilePath'):
            strName = dicRead['FilePath'].strip()

        if len(strName) and (strName != self.__m_strNameOfFile):
            self.__m_strNameOfFile = strName
            self.__m_file = ConfigObj(self.__m_strNameOfFile, encoding='UTF8')

        if not self.__m_file:
            return -100

        dicRead['SectionList'] = self.__m_file.keys()
        ir = 1
        try:
            dicRead['OptionDic'] = self.__m_file[dicRead['Section']]
            ir = 2
            dicRead['Value'] = self.__m_file[dicRead['Section']][dicRead['Option']]
            ir = 3
        except Exception as e:
            pass

        return ir

    # 写配置文件
    def f_Write(self, dicWrite={'Section': 0, 'Option': 0, 'Value': 0, 'FilePath': ''}):
        """
        function:  Write Dic into INI.file
              in:  The parameter Dic that needs to be written to ini file； Parameter Dic Has Strict Requirements
                   param dicRead: 需要写入配置文件的参数Dic
                   Section : ini文件中带[]的项
                   FilePath : 文件路径
                   Option : 选项
                   Value : 具体的值
             out:  None
          return:  int >0 ok, <0 somewrong
          others:  写配置文件，一次只能写入一个键值对，需要文件存在的前提下才能写
        """
        ir = 0
        strName = ''
        if dicWrite.get('FilePath'):
            strName = dicWrite['FilePath'].strip()
        if len(strName) and (strName != self.__m_strNameOfFile):
            self.__m_strNameOfFile = strName
            self.__m_file = ConfigObj(self.__m_strNameOfFile, encoding='UTF8')
        if not self.__m_file:
            return -100
        try:
            self.__m_file[dicWrite['Section']][dicWrite['Option']] = dicWrite['Value']
            self.__m_file.write()
            ir = 1
        except Exception as e:
            ir = -200
        return ir

    # 创建配置文件
    def f_Create(self, dicWrite={'Section': 0, 'Option': 0, 'Value': 0, 'FilePath': ''}):
        """
        function:  if fielpath is not exist ，create file amd write Dic into INI.file
              in:  The parameter Dic that needs to be written to ini file； Parameter Dic Has Strict Requirements
                   param dicRead: 需要写入配置文件的参数Dic
                   Section : ini文件中带[]的项
                   FilePath : 文件路径
                   Option : 选项
                   Value : 具体的值
             out:  None
          return:  int >0 ok, <0 somewrong
          others:  写配置文件，一次只能写入一个键值对，文件路径不存在则创建
        """
        ir = 0
        strName = ''
        if dicWrite['FilePath']:
            strName = dicWrite['FilePath'].strip()
        if len(strName) and (strName != self.__m_strNameOfFile):
            self.__m_strNameOfFile = strName
            print(strName)
            self.__m_file = ConfigObj(self.__m_strNameOfFile, encoding='UTF8')
            # create section
        try:
            section = self.__m_file[dicWrite['Section']]
        except Exception as e:
            self.__m_file[dicWrite['Section']] = {}
            # create option
        try:
            self.__m_file[dicWrite['Section']][dicWrite['Option']] = dicWrite['Value']
            self.__m_file.write()
            ir = 1
        except Exception as e:
            ir = -200
        return ir

    # 清空配置文件
    def f_Clear(self, dicWrite={'Section': 0, 'FilePath': ''}):
        """
        function:  清空配置文件
              in:  dicWrite={'Section': 0, 'FilePath': ''}
             out:  ir
          return:  int >0 ok, <0 somewrong
          others:  Clear Configuration File
        """
        ir = 0
        strName = ''
        if dicWrite.get('FilePath'):
            strName = dicWrite['FilePath'].strip()
        if len(strName) and (strName != self.__m_strNameOfFile):
            self.__m_strNameOfFile = strName
            self.__m_file = ConfigObj(self.__m_strNameOfFile, encoding='UTF8')
        if not self.__m_file:
            return -100
        try:
            del self.__m_file[dicWrite['Section']]
            self.__m_file.write()
            ir = 1
        except Exception as e:
            ir = -200
        return ir


if __name__ == '__main__':
    def ReadInstance():
        """
        function:  Read INI File Example
              in:  None
             out:  None
          return:  int >0 ok, <0 somewrong 
          others:  使用tFileINI.f_Read()方法
        """
        filePath = "E:\\Python\\20211230上位机代码及相关文档\\上位机代码及相关文档\\code\\py\\tdata\\ModuleConfig.cfg"
        dic = {}
        ConfigFile = ctIniHelper(filePath)
        dicR = {}
        ir = ConfigFile.f_Read(dicR)
        # SectionList：ini文件中带[]的项的列表
        listSects = dicR['SectionList']
        n = len(listSects)
        # 端口 列表
        for i in range(0, n):
            PortID = listSects[i]
            dicR['Section'] = PortID
            ir = ConfigFile.f_Read(dicR)
            # SectionList': ['1', '100', '104', '101', '103', '102', '105', '106', '117', '107']
            # 'Section': '1'
            # 'OptionDic': {'ConfigNote': 'pc serial default', 'CardAddr': '10', 'CardID': '10', 'ClassID': '1001'}
            dicR = dicR['OptionDic']
            # print(dicR)
            configNote = dicR['ConfigNote']
            cardAddr = dicR['CardAddr']
            cardID = dicR['CardID']
            classID = dicR['ClassID']
            dic[i + 1] = [PortID, configNote, cardAddr, cardID, classID]


    def CreateInstance():
        """
        function:
              in:
             out:
          return:  int >0 ok, <0 somewrong
          others:
        """
        filePath = "E:\\Python\\1.cfg"
        dicR = {'Section': '1', 'Option': 'CardAddr', 'Value': '123', "FilePath": f"{filePath}"}
        dicR1 = {'Section': '2', 'Option': 'ConfigNote', 'Value': '复位及启动指令1', "FilePath": f"{filePath}"}
        dicR2 = {'Section': '1', "FilePath": f"{filePath}"}
        dicR3 = {'Section': '2', "FilePath": f"{filePath}"}
        ConfigFile = ctIniHelper(filePath)
        # ir = ConfigFile.f_Write(dicR)
        # ir = ConfigFile.f_Create(dicR)
        # ir = ConfigFile.f_Create(dicR1)
        ConfigFile.f_Clear(dicR2)
        ConfigFile.f_Clear(dicR3)


    # ReadInstance()
    CreateInstance()
